<?php

class Controller_Offer extends Controller_Abstract
{
	function actionMorecredit()
	{
		if(!isset($this->_view['user'])){
			return $this->_redirect(url('user/signup'));
		}
		$sitemodel = new Site();
		$monetizationIds = $sitemodel->getMonetizationIds($this->_site['id']);
		$monetizationmodel = new Monetization();
		$ms = array();
		$monetizations = array();
		if (!empty($monetizationIds['monetization1']))
		{
			$m = $monetizationmodel->getMonetizationById($monetizationIds['monetization1']);
			if ($m != false)
			{
				$ms[] = $m;
				$monetizations[0] = $m['name'];
			}
		}
		if (!empty($monetizationIds['monetization2']))
		{
			$m = $monetizationmodel->getMonetizationById($monetizationIds['monetization2']);
			if ($m != false)
			{
				$ms[] = $m;
				$monetizations[1] = $m['name'];
			}
		}
		if (!empty($monetizationIds['monetization3']))
		{
			$m = $monetizationmodel->getMonetizationById($monetizationIds['monetization3']);
			if ($m != false)
			{
				$ms[] = $m;
				$monetizations[2] = $m['name'];
			}
		}
		if (!empty($monetizationIds['monetization4']))
		{
			$m = $monetizationmodel->getMonetizationById($monetizationIds['monetization4']);
			if ($m != false)
			{
				$ms[] = $m;
				$monetizations[3] = $m['name'];
			}
		}
		
		$this->_view['monetizations'] = $ms;
//		$this->_view['monetizations'] = $monetizationmodel->getMonetizationByIds($monetizationIds);
		
		//TODO: recording more credits
		
		$record = new Record($this->_view['user']['id']);
		//prepare monetizations
		$monetizations += array('', '', '', '');
		$record->addMoreCreditsViewRecording($monetizations);
		
		//setcookie('reftip', null);
		$domain = $this->_view['site']['domain'];
		$tipModel = new TipManager();
		$tipArray = $tipModel->getTipByFields( array('domain' => $domain, 'controller_view' => 'offer_morecredit') );
		$this->_view['tips'] = isset($tipArray[$domain]['offer_morecredit'])? $tipArray[$domain]['offer_morecredit'] : array();
		if(isset($_COOKIE['reftip'])){
			$_COOKIE['reftip'] = 'old';
		}else{
			setcookie('reftip', 'new', time()+60*60*24*365*10);
		}
		
		return $this->display($this->_site['template']);
	}
	
	function actionSrvideo()
	{
		$user = $this->_app->currentUser();
		$userid = $user['id'];
		$ip = Util::getClientIp();
		$h = $this->_context->h;
		$file = "http://www.superrewards-offers.com/super/offers?uid=$userid&xml=1&v=3&ip=$ip&hdpay=1&mode=video";
		if($h != null){
			$file .= "&h=$h";
		}
		$s = simplexml_load_file($file);

//	    $i=0;
//	    $counter = count($s->offers->offer);
//		while($i<$counter)
//		{
//			echo "offer: ".$i."<br/>";
//			echo '<img src="'. $s->offers->offer[$i]->image . '"><br/>';
//			echo "id: ".$s->offers->offer[$i]['id']."<br/>";
//			echo "name: ".$s->offers->offer[$i]->title."<br/>";
//			echo "description: ".$s->offers->offer[$i]->description."<br/>";
//			echo "payout: ".$s->offers->offer[$i]->payout."<br/>";
//			echo "type: ".$s->offers->offer[$i]['offer_type']."<br/>";
//			echo "requirements: ".$s->offers->offer[$i]->requirements."<br/>";
//			echo "price points: ".$s->offers->offer[$i]->price_points->price[0]['amount'].",".$s->offers->offer[$i]->price_points->price[1]['amount'].",".$s->offers->offer[$i]->price_points->price[2]['amount']."<br/>";
//			$i++;
//			echo '<a href="' . $s->offers->offer[$i]->click_url. '">link to offer</a><br><br>';
//		}
//		exit;
		
		$this->_view['s'] = $s;
		return $this->display($this->_site['template']);
	}
	
	function actionCoreg()
	{
		$this->_view['redirect_url'] = $_SESSION['redirect_url'];//	dump($_SESSION['redirect_url']);
		unset($_SESSION['redirect_url']);
		return $this->display($this->_site['template']);
	}	
	
	function actionDailydeals()
	{
		$dailyDealsModel = new DailyDeals();
		$dailyDealsOffers = $dailyDealsModel->getDailyDealsOffers($this->_site['id'], date('Y-m-d'));
		$this->_view['dailyDealsOffers'] = $dailyDealsOffers;
		
		return $this->display($this->_site['template']);
	}
	
	function actionGetdailydealsoffer()
	{
//		$id = $this->_context->get('id', 0);
//		$dailyDealsModel = new DailyDeals();
//		$dailyDealsOffer = $dailyDealsModel->getDailyDealsOfferById($id);
//		$dailyDealsOffer['link_url'] = str_replace(
//			array('INSERT_END_USER_ID'), 
//			array($this->_view['user']['id']),
//			$dailyDealsOffer['link_url']
//		);
//		$dailyDealsOffer['timeRemaining'] = strftime('%H:%M:%S', strtotime($dailyDealsOffer['end_date']) - time());
//		
//		return json_encode($dailyDealsOffer);
	}
	
	function actionPaymentwall()
	{
		//authorize the request
		$allowedIps = array(
			"66.220.10.2",
			"66.220.10.3",
			"174.36.92.186",
			"174.36.96.66",
			"174.36.92.187",
			"174.36.92.192",
			"174.37.14.28",
		);
//		$clientIp = $this->_context->server('REMOTE_ADDR');
//		$index = array_search($clientIp, $allowedIps);
		
		//an illegal request
//		if(false !== $index){
		if (true)
		{
			// application secret key
			$uid = $this->_context->uid;
			$amount = $this->_context->currency;
			$type = $this->_context->type;
			$pid = $this->_context->ref;
			$sig = $this->_context->sig;
			
			if ($this->_site['id'] == 1)
			{
				$secretKey = 'a23226cc9ec1e245b51fd631e2cb1be0';
			}
			else if ($this->_site['id'] == 2)
			{
				$secretkey = '92d1df5e95d05e7024f62bc8492ef182';
			}
			else
			{
				$secretKey = '80b67f7cb18ba452db288875fb883cbb';
			}
			$toEnctype = sprintf("uid=%scurrency=%stype=%sref=%s%s", $uid, $amount, $type, $pid, $secretKey);
			//validate the callback
			//sig = MD5(uid=[USER_ID]currency=[VIRTUAL_CURRENCY]type=[TYPE]ref=[REF][SECRET_KEY])
			if(md5($toEnctype) == $sig)
			{
				//0 – when a credit is given
				if(intval($type) == 0)
				{
					$rewardmodel = new Reward();
					$name = 'Payment Wall '. $pid;
					$usermodel = new User();
					$flag = $usermodel->offerUserCredits($amount, $uid);
					if($flag)
					{
						$offermodel = new Reward();
						$offermodel->addRewardByMonetization($uid, $name, $amount, $pid);
				
						if ($this->_site['game'] == WHEEL)
						{
							$siteFactor = 1;
						}
						else if ($this->_site['game'] == SLOT)
						{
							$siteFactor = 0.15;
						}
						else if ($this->_site['game'] == POKER)
						{
							$siteFactor = 1;
						}
						$mmodel = new Monetization();
						$revenue = $siteFactor * $mmodel->getMonetizationFactor('payment_wall_token_value') * $amount;
				
						$record = new Record($uid);
						$record->addOfferCallbackRecording($amount, $revenue, 'Payment Wall');

						$site = new Site();
						if ($this->_site['game'] == SLOT)
						{
							$site->updateJackpot($this->_site['id'], round($amount/5));
						}
						else
						{
							$site->updateJackpot($this->_site['id'], $amount);
						}
					
						$user = $usermodel->getUserById($uid);
						if($user['cam'] == '17' || $user['cam'] == '18'){
							if($user['fired'] != '1'){
								$s2scamModel = new S2scam();
								$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
								$usermodel->setFired($user['id']);
							}
						}
						echo "OK";
					}
					else
					{
						header("HTTP/1.0 403 Failure - do not retry");
					}
				}
				else if (intval($type)== 2)
				{
					$rewardmodel = new Reward();
					$name = 'ChargeBack: Payment Wall '. $pid;
					$usermodel = new User();
					$flag = $usermodel->offerUserCredits($amount, $uid);
					if($flag)
					{
						$offermodel = new Reward();
						$offermodel->addRewardByMonetization($uid, $name, $amount, $pid);
				
						$mmodel = new Monetization();
						$revenue = $siteFactor * $mmodel->getMonetizationFactor('payment_wall_token_value') * $amount;
				
						$record = new Record($uid);
						$record->addOfferCallbackRecording($amount, $revenue, 'Payment Wall');

						echo "OK";
					}
					else
					{
						header("HTTP/1.0 403 Failure - do not retry");
					}
				}
			}
			else 
			{
				//will retry 30 minutes
	            header("HTTP/1.0 403 Failure - do not retry");
	        }
		}
		else
		{
			//Unauthorized
		}
	}
	
	
	function actionPeanutlabs()
	{
		$status = $this->_context->status;
		if ($status != 'C')
		{
			echo '1';
			exit;
		}
		$hash = $this->_context->oidHash;
		$uid = $this->_context->userId;
		$uid = explode('-', $uid);
		$uid = $uid[0];
		if (empty($uid))
		{
			echo '0';
			exit;
		}
		
		$pid = $this->_context->transactionId;
		if (empty($pid))
		{
			$pid = 0;
		}
		$amount = $this->_context->currencyAmt;
		$oid = $this->_context->offerInvitationId;
		$money = $this->_context->amt;
		if (empty($this->_context->m))
		{
			if ($this->_site['game'] == WHEEL)
			{
				$mid = 5;
			}
			else if ($this->_site['game'] == SLOT)
			{
				$mid = 6;
			}
			else if ($this->_site['game'] == POKER)
			{
				$mid = 9;
			}
		}
		else
		{
			$mid = $this->_context->m;
		}
		$mmodel = new Monetization();
/*		if (!empty($this->_context->bluebarid) || (!empty($this->_context->bannerid))){
			if ($this->_site['game'] == POKER)
			{
				$secretKey = 'eeef3bb8ea124f52b7d1344b23d04f23';
			}
			else if ($this->_site['game'] == WHEEL)
			{
				$secretKey = 'fb487846e1a441dc8a39e43bf96e1588';
			}
			else if ($this->_site['game'] == SLOT)
			{
				$secretKey = '2367167600984aea8c485969974a9661';
			}			
		}else{
*/
			$secretKey = $mmodel->getSecretKeyById($mid);			
//		}

		if ($secretKey == false)
		{
			echo '0';
			exit;
		}

		if (md5($oid. $secretKey) == $hash)
		{
			$rewardmodel = new Reward();
			if ($rewardmodel->exists($uid, $pid))
			{
				echo '1';
				exit;
			}
			$name = 'Peanut Labs '. $pid;
			$usermodel = new User();
			$flag = $usermodel->offerUserCredits($amount, $uid);
			if($flag)
			{
				$offermodel = new Reward();
				$offermodel->addRewardByMonetization($uid, $name, $amount, $pid, $oid, $money);
				
				//TODO: peanut labs offer callback
				
				if ($this->_site['game'] == WHEEL)
				{
					$siteFactor = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$siteFactor = 0.15;
				}
				else if ($this->_site['game'] == POKER)
				{
					$siteFactor = 1;
				}
				
				$revenue = $siteFactor * $mmodel->getMonetizationFactor('peanut_labs_token_value') * $amount;
				
				$record = new Record($uid);
				$record->addOfferCallbackRecording($amount, $revenue, 'Peanut Labs');

				$site = new Site();
				if ($this->_site['game'] == SLOT)
				{
					$site->updateJackpot($this->_site['id'], round($amount/5));
				}
				else
				{
					$site->updateJackpot($this->_site['id'], $amount);
				}
				if (!empty($this->_context->em))
				{
					$emodel = new Email();
					$emodel->updateCompleted($this->_context->em);
					
					$email = $emodel->getEmailInfoById($this->_context->em);
					if(!empty($email)){
						$email_created_hour = $email['created'] - $email['created'] % (60*60);
						
						$record = new Record($uid);
						$record->addEmailOfferCompleteRecording($email['email_type'], date('YmdHis', $email_created_hour));
					}
				}
				if (!empty($this->_context->bluebarid))
				{
					$record = new Record($uid);
					$record->addBlueBarOfferCompleteRecording($this->_context->bluebarid);
				}
				if (!empty($this->_context->bannerid))
				{
					$record = new Record($uid);
					$record->addBannerOfferCompleteRecording($this->_context->bannerid);
				}
				if (!empty($this->_context->dailydealsid))
				{
					$record = new Record($uid);
					$record->addDailyDealsOfferCompleteRecording($this->_context->dailydealsid);
				}
				
				$user = $usermodel->getUserById($uid);
				if($user['cam'] == '17' || $user['cam'] == '18'){
					if($user['fired'] != '1'){
						$s2scamModel = new S2scam();
						$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
						$usermodel->setFired($user['id']);
					}
				}
				echo '1';
			}
			else
			{
				echo '0';
			}				
		}
		else
		{
			echo '0';
		}
		exit;
	}
	
	function actionRadiumone()
	{
		$trackId = $this->_context->trackId;
		if (empty($trackId))
		{
			echo '0';
			exit;
		}
		if (intval($trackId) > 100)
		{
			if ($this->_site['game'] == WHEEL)
			{
				$trackId = 'cdleft';
			}
			else if ($this->_site['game'] == SLOT)
			{
				$trackId = 'llleft';
			}
			else if ($this->_site['game'] == POKER)
			{
				$trackId = 'mmleft';
			}
		}
		$mmodel = new Monetization();
		if ($trackId == 'mmtop')
		{
			$secretKey = '067125b7459548259422a0e611470358';
		}
		else if ($trackId == 'llltop')
		{
			$secretKey = 'c3315fbf97f74199876724335fa83cfe';
		}
		else if ($trackId == 'cdtop')
		{
			$secretKey = '874e44c00d6f4ad1a4da9e9db125b943';
		}
		else if ($trackId == 'mmleft')
		{
			$secretKey = 'eeef3bb8ea124f52b7d1344b23d04f23';
		}
		else if ($trackId == 'lllleft')
		{
			$secretKey = 'fb487846e1a441dc8a39e43bf96e1588';
		}
		else if ($trackId == 'cdleft')
		{
			$secretKey = '2367167600984aea8c485969974a9661';
		}
		else if ($trackId == 'ukcdtop')
		{
			$secretKey = 'b4ebe396e6144ca68e88ab0dc614cba7';
		}
		else if ($trackId == 'ukllltop')
		{
			$secretKey = '8f21a6ec150c4bee853c8e4623fdd69c';
		}
		else if ($trackId == 'ukmmtop')
		{
			$secretKey = 'b151ac25ea1b4668a206b0b60699d4b0';
		}
		else if(strpos($trackId, 'bluebarid_') == 0 || strpos($trackId, 'bannerid_') == 0){
			if ($this->_site['game'] == POKER)
			{
				$secretKey = 'eeef3bb8ea124f52b7d1344b23d04f23';
			}
			else if ($this->_site['game'] == SLOT)
			{
				$secretKey = 'fb487846e1a441dc8a39e43bf96e1588';
			}
			else if ($this->_site['game'] == WHEEL)
			{
				$secretKey = '2367167600984aea8c485969974a9661';
			}
		}
		else
		{
			$secretKey = $mmodel->getSecretKeyById($trackId);
		}
		if ($secretKey == false)
		{
			echo '0';
			exit;
		}
		$userId = $this->_context->userId;
		$appId = $this->_context->appId;
		$amount = $this->_context->amount;
		$pid = $this->_context->pid;
		$hash = $this->_context->hash;
		$chargeback = $this->_context->chargeback;
		$toEnctype = sprintf("%s:%s:%s", $userId, $appId, $secretKey);
		$name = "Radium One " . $pid;
		if(md5($toEnctype) == $hash)
		{
			$offermodel = new Reward();
			if ($offermodel->exists($userId, $pid))
			{
				echo '1';
				exit;
			}

			$usermodel = new User();			
			$flag = $usermodel->offerUserCredits($amount, $userId);
			if($flag)
			{
				$offermodel = new Reward();
				$offermodel->addRewardByMonetization($userId, $name, $amount, $pid);
				
				//TODO: radiumone offer call back
				
				if ($this->_site['game'] == WHEEL)
				{
					$siteFactor = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$siteFactor = 0.15;
				}
				else if ($this->_site['game'] == POKER)
				{
					$siteFactor = 1;
				}
				
				$revenue = $siteFactor * $mmodel->getMonetizationFactor('radium_one_token_value') * $amount;
				
				$record = new Record($userId);
				$record->addOfferCallbackRecording($amount, $revenue, 'Radium One');
				
				$site = new Site();
				if ($this->_site['game'] == SLOT)
				{
					$site->updateJackpot($this->_site['id'], round($amount/5));
				}
				else
				{
					$site->updateJackpot($this->_site['id'], $amount);
				}
				if (!empty($this->_context->trackId))
				{
					if(strpos($this->_context->trackId, 'bluebarid_') == 0){
						$blueBarOfferId = str_replace('bluebarid_', '', $this->_context->trackId);
						$record = new Record($userId);
						$record->addBlueBarOfferCompleteRecording($blueBarOfferId);
					}else if(strpos($this->_context->trackId, 'bannerid_') == 0){
						$bannerOfferId = str_replace('bannerid_', '', $this->_context->trackId);
						$record = new Record($userId);
						$record->addBannerOfferCompleteRecording($bannerOfferId);
					}else if(strpos($this->_context->trackId, 'dailydealsid_') == 0){
						$dailyDealsOfferId = str_replace('dailydealsid_', '', $this->_context->trackId);
						$record = new Record($userId);
						$record->addBannerOfferCompleteRecording($dailyDealsOfferId);
					}else{
						$emodel = new Email();
						$emodel->updateCompleted($this->_context->trackId);
						
						$email = $emodel->getEmailInfoById($this->_context->trackId);
						if(!empty($email)){
							$email_created_hour = $email['created'] - $email['created'] % (60*60);
							
							$record = new Record($userId);
							$record->addEmailOfferCompleteRecording($email['email_type'], date('YmdHis', $email_created_hour));
						}		
					}

				}
				
				$user = $usermodel->getUserById($userId);
				if($user['cam'] == '17' || $user['cam'] == '18'){
					if($user['fired'] != '1'){
						$s2scamModel = new S2scam();
						$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
						$usermodel->setFired($user['id']);
					}
				}
				echo '1';
			}
			else
			{
				echo '0';
			}				
		}
		else
		{
			echo '0';
		}
		exit;
	}

	function actionPartialradiumone()
	{
		$mmodel = new Monetization();
		if ($this->_site['game'] == POKER)
		{
			$secretKey = 'bc5ee25caf8d4fb0924f7f17de898f21';
		}
		else if ($this->_site['game'] == SLOT)
		{
			$secretKey = 'da666afe01b746e08171d0733a8ed494';
		}
		else if ($this->_site['game'] == WHEEL)
		{
			$secretKey = '708a5662ea5247cca433bbac4d028746';
		}
		if ($secretKey == false)
		{
			echo '0';
			exit;
		}
		$userId = $this->_context->userId;
		$appId = $this->_context->appId;
		$amount = $this->_context->amount;
		$pid = $this->_context->pid;
		$hash = $this->_context->hash;
		$chargeback = $this->_context->chargeback;
		$toEnctype = sprintf("%s:%s:%s", $userId, $appId, $secretKey);
		$name = "(Partial)Radium One " . $pid;
		if(md5($toEnctype) == $hash)
		{
			$offermodel = new Reward();
			if ($offermodel->exists($userId, $pid))
			{
				echo '1';
				exit;
			}

			$usermodel = new User();			
			$flag = $usermodel->offerUserPartialCredits($amount, $userId);
			if($flag)
			{
				$offermodel = new Reward();
				$offermodel->addRewardByMonetization($userId, $name, $amount, $pid);
				
				if ($this->_site['game'] == WHEEL)
				{
					$siteFactor = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$siteFactor = 0.15;
				}
				else if ($this->_site['game'] == POKER)
				{
					$siteFactor = 1;
				}

				$revenue = $siteFactor * $mmodel->getMonetizationFactor('radium_one_token_value') * $amount * 0.01;
				
				$record = new Record($userId);
				$record->addOfferCallbackRecording($amount, $revenue, 'Radium One Partial');
				
				if (!empty($this->_context->trackId))
				{
					if(strpos($this->_context->trackId, 'bluebarid_') == 0){
						$blueBarOfferId = str_replace('bluebarid_', '', $this->_context->trackId);
						$record = new Record($userId);
						$record->addBlueBarOfferCompleteRecording($blueBarOfferId);
					}else if(strpos($this->_context->trackId, 'bannerid_') == 0){
						$bannerOfferId = str_replace('bannerid_', '', $this->_context->trackId);
						$record = new Record($userId);
						$record->addBannerOfferCompleteRecording($bannerOfferId);
					}else if(strpos($this->_context->trackId, 'dailydealsid_') == 0){
						$dailyDealsOfferId = str_replace('dailydealsid_', '', $this->_context->trackId);
						$record = new Record($userId);
						$record->addBannerOfferCompleteRecording($dailyDealsOfferId);
					}else{
						$emodel = new Email();
						$emodel->updateCompleted($this->_context->trackId);
						
						$email = $emodel->getEmailInfoById($this->_context->trackId);
						if(!empty($email)){
							$email_created_hour = $email['created'] - $email['created'] % (60*60);
							
							$record = new Record($userId);
							$record->addEmailOfferCompleteRecording($email['email_type'], date('YmdHis', $email_created_hour));
						}		
					}

				}
				
				$user = $usermodel->getUserById($userId);
				if($user['cam'] == '17' || $user['cam'] == '18'){
					if($user['fired'] != '1'){
						$s2scamModel = new S2scam();
						$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
						$usermodel->setFired($user['id']);
					}
				}
				echo '1';
			}
			else
			{
				echo '0';
			}				
		}
		else
		{
			echo '0';
		}
		exit;
	}
	
	function actionSponsorselect(){
		$offer = new Offer();
		$offer->addOfferByMonetization(11, 'test', 11);
	}
	
	function actionSponsorpay()
	{
		$hash = $this->_context->sid;
		$uid = $this->_context->uid;
		if (empty($uid))
		{
			header(Util::HTTPStatus(400));
			exit;
		}
		
		$pid = $this->_context->_trans_id_;
		if (empty($pid))
		{
			$pid = 0;
		}
		$amount = $this->_context->amount;
		$mmodel = new Monetization();
/*		$mid = $this->_context->pub0;
		$secretKey = $mmodel->getSecretKeyById($mid);
		if ($secretKey == false)
		{
			header(Util::HTTPStatus(400));
			exit;
		}
*/
/*		if (!empty($this->_context->pub2)){
			if ($this->_site['game'] == POKER)
			{
				$secretKey = 'eeef3bb8ea124f52b7d1344b23d04f23';
			}
			else if ($this->_site['game'] == WHEEL)
			{
				$secretKey = 'fb487846e1a441dc8a39e43bf96e1588';
			}
			else if ($this->_site['game'] == SLOT)
			{

				$secretKey = '2367167600984aea8c485969974a9661';
			}			
		}else{
*/
			$secretKey = 'arthur@cgb.com';
//		}
		$pub0 = $this->_context->pub0;
		if (empty($pub0))
		{
			$pub0 = '';
		}
		$pub1 = $this->_context->pub1;
		if (empty($pub1))
		{
			$pub1 = '';
		}
		$pub2 = $this->_context->pub2;
		if (empty($pub2))
		{
			$pub2 = '';
		}
		if (sha1($secretKey.$uid. $amount.$pid.$pub0.$pub1.$pub2) == $hash)
		{
			$rewardmodel = new Reward();
			if ($rewardmodel->exists($uid, $pid))
			{
				//dupe
				exit;
			}
			$name = 'SponsorPay '. $pid;
			$usermodel = new User();
			$flag = $usermodel->offerUserCredits($amount, $uid);
			if($flag)
			{
				$offermodel = new Reward();
				$offermodel->addRewardByMonetization($uid, $name, $amount, $pid);
				
				if ($this->_site['game'] == WHEEL)
				{
					$siteFactor = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$siteFactor = 0.15;
				}
				else if ($this->_site['game'] == POKER)
				{
					$siteFactor = 1;
				}
				
				$revenue = $siteFactor * $mmodel->getMonetizationFactor('sponsorpay_token_value') * $amount;
				
				$record = new Record($uid);
				$record->addOfferCallbackRecording($amount, $revenue, 'SponsorPay');

				$site = new Site();
				if ($this->_site['game'] == SLOT)
				{
					$site->updateJackpot($this->_site['id'], round($amount/5));
				}
				else
				{
					$site->updateJackpot($this->_site['id'], $amount);
				}
				if (!empty($this->_context->pub1))
				{
					$emodel = new Email();
					$emodel->updateCompleted($this->_context->pub1);
					
					$email = $emodel->getEmailInfoById($this->_context->pub1);
					if(!empty($email)){
						$email_created_hour = $email['created'] - $email['created'] % (60*60);
						
						$record = new Record($uid);
						$record->addEmailOfferCompleteRecording($email['email_type'], date('YmdHis', $email_created_hour));
					}
				}
				if (!empty($this->_context->pub2))
				{
					$record = new Record($uid);
					$record->addBlueBarOfferCompleteRecording($this->_context->pub2);
				}
				if (!empty($this->_context->pub3))
				{
					$record = new Record($uid);
					$record->addBannerOfferCompleteRecording($this->_context->pub3);
				}
				if (!empty($this->_context->pub4))
				{
					$record = new Record($uid);
					$record->addDailyDealsOfferCompleteRecording($this->_context->pub4);
				}
				
				$user = $usermodel->getUserById($uid);
				if($user['cam'] == '17' || $user['cam'] == '18'){
					if($user['fired'] != '1'){
						$s2scamModel = new S2scam();
						$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
						$usermodel->setFired($user['id']);
					}
				}
			}
			else
			{
				header(Util::HTTPStatus(500));
			}				
		}
		else
		{
			header(Util::HTTPStatus(401));
		}
		exit;
	}
	
	function actionSuperrewards()
	{
		$pid = $this->_context->id;
		$amount = $this->_context->new;
		$uid = $this->_context->uid;
		$hash = $this->_context->sig;
		$mid = $this->_context->custom_m;
		$oid = $this->_context->oid;
/*		if (!empty($this->_context->custom_bluebar) || !empty($this->_context->custom_banner)){
			if ($this->_site['game'] == POKER)
			{
				$secretKey = 'eeef3bb8ea124f52b7d1344b23d04f23';
			}
			else if ($this->_site['game'] == WHEEL)
			{
				$secretKey = 'fb487846e1a441dc8a39e43bf96e1588';
			}
			else if ($this->_site['game'] == SLOT)
			{
				$secretKey = '2367167600984aea8c485969974a9661';
			}			
		}else{
*/
			if (empty($mid))
			{
				if ($this->_site['game'] == WHEEL)
				{
					$secretKey = '4031e2055870adc60122377b704e8f6d';
				}
				else if ($this->_site['game'] == SLOT)
				{
					$secretKey = '206ed9d4945b2bb4748f0e333a223574';
				}
				else if ($this->_site['game'] == POKER)
				{
					$secretKey = 'a6fed15e1f4989d9659df991636b4ea6';
				}
			}
			else
			{
				$mmodel = new Monetization();
				$secretKey = $mmodel->getSecretKeyById($mid);
			}			
//		}

		if ($secretKey == false)
		{
			echo '0';
			exit;
		}
		$name = 'Super Rewards '. $pid;
		if (md5($pid. ':'. $amount . ':'. $uid. ':'. $secretKey) == $hash)
		{
			$offermodel = new Reward();
			if ($offermodel->exists($uid, $pid))
			{
				echo '1';
				exit;
			}

			$usermodel = new User();			
			$flag = $usermodel->offerUserCredits($amount, $uid);
			if($flag)
			{
				$offermodel->addRewardByMonetization($uid, $name, $amount, $pid, $oid);
				
				if ($this->_site['game'] == WHEEL)
				{
					$siteFactor = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$siteFactor = 0.15;
				}
				else if ($this->_site['game'] == POKER)
				{
					$siteFactor = 1;
				}
				
				$revenue = $siteFactor * $mmodel->getMonetizationFactor('super_reward_token_value') * $amount;
				
				//TODO: super rewards offer call back
				$record = new Record($uid);
				$record->addOfferCallbackRecording($amount, $revenue, 'Super Rewards');

				$site = new Site();
				if ($this->_site['game'] == SLOT)
				{
					$site->updateJackpot($this->_site['id'], round($amount/5));
				}
				else
				{
					$site->updateJackpot($this->_site['id'], $amount);
				}
				if (!empty($this->_context->custom_em))
				{
					$emodel = new Email();
					$emodel->updateCompleted($this->_context->custom_em);
					
					$email = $emodel->getEmailInfoById($this->_context->custom_em);
					if(!empty($email)){
						$email_created_hour = $email['created'] - $email['created'] % (60*60);
						
						$record = new Record($uid);
						$record->addEmailOfferCompleteRecording($email['email_type'], date('YmdHis', $email_created_hour));
					}
				}
				if (!empty($this->_context->custom_bluebar))
				{
					$record = new Record($uid);
					$record->addBlueBarOfferCompleteRecording($this->_context->custom_bluebar);
				}
				if (!empty($this->_context->custom_banner))
				{
					$record = new Record($uid);
					$record->addBannerOfferCompleteRecording($this->_context->custom_banner);
				}
				if (!empty($this->_context->custom_dailydeals))
				{
					$record = new Record($uid);
					$record->addBannerOfferCompleteRecording($this->_context->custom_dailydeals);
				}
				
				$user = $usermodel->getUserById($uid);
				if($user['cam'] == '17' || $user['cam'] == '18'){
					if($user['fired'] != '1'){
						$s2scamModel = new S2scam();
						$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
						$usermodel->setFired($user['id']);
					}
				}
				echo '1';
			}
			else
			{
				echo '0';
			}				
		}
		else
		{
			echo '0';
		}
		exit;
	}
	function actionPartialsuperrewards()
	{
		$pid = $this->_context->id;
		$amount = $this->_context->new;
		$uid = $this->_context->uid;
		$hash = $this->_context->sig;
		$mid = $this->_context->custom_m;
		$oid = $this->_context->oid;
		if (empty($mid))
		{
			if ($this->_site['game'] == WHEEL)
			{
				$secretKey = '4031e2055870adc60122377b704e8f6d';
			}
			else if ($this->_site['game'] == SLOT)
			{
				$secretKey = '206ed9d4945b2bb4748f0e333a223574';
			}
			else if ($this->_site['game'] == POKER)
			{
				$secretKey = 'a6fed15e1f4989d9659df991636b4ea6';
			}
		}
		else
		{
			$mmodel = new Monetization();
			$secretKey = $mmodel->getSecretKeyById($mid);
		}
		if ($secretKey == false)
		{
			echo '0';
			exit;
		}
		$name = '(Partial)Super Rewards '. $pid;
		if (md5($pid. ':'. $amount . ':'. $uid. ':'. $secretKey) == $hash)
		{
			$offermodel = new Reward();
			if ($offermodel->exists($uid, $pid))
			{
				echo '1';
				exit;
			}

			$usermodel = new User();			
			$flag = $usermodel->offerUserPartialCredits($amount, $uid);
			if($flag)
			{
				$offermodel->addRewardByMonetization($uid, $name, $amount, $pid, $oid);
				
				if ($this->_site['game'] == WHEEL)
				{
					$siteFactor = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$siteFactor = 0.15;
				}
				else if ($this->_site['game'] == POKER)
				{
					$siteFactor = 1;
				}
				
				$revenue = $siteFactor * $mmodel->getMonetizationFactor('super_reward_token_value') * $amount * 0.01;
				
				//TODO: super rewards offer call back
				$record = new Record($uid);
				$record->addOfferCallbackRecording($amount, $revenue, 'Super Rewards Partial');

				$site = new Site();
				if (!empty($this->_context->custom_em))
				{
					$emodel = new Email();
					$emodel->updateCompleted($this->_context->custom_em);
					
					$email = $emodel->getEmailInfoById($this->_context->custom_em);
					if(!empty($email)){
						$email_created_hour = $email['created'] - $email['created'] % (60*60);
						
						$record = new Record($uid);
						$record->addEmailOfferCompleteRecording($email['email_type'], date('YmdHis', $email_created_hour));
					}
				}
				if (!empty($this->_context->custom_bluebar))
				{
					$record = new Record($uid);
					$record->addBlueBarOfferCompleteRecording($this->_context->custom_bluebar);
				}
				if (!empty($this->_context->custom_dailydeals))
				{
					$record = new Record($uid);
					$record->addBlueBarOfferCompleteRecording($this->_context->custom_dailydeals);
				}
				
				$user = $usermodel->getUserById($uid);
				if($user['cam'] == '17' || $user['cam'] == '18'){
					if($user['fired'] != '1'){
						$s2scamModel = new S2scam();
						$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
						$usermodel->setFired($user['id']);
					}
				}
				echo '1';
			}
			else
			{
				echo '0';
			}				
		}
		else
		{
			echo '0';
		}
		exit;
	}
	
	function actionEpicsocial()
	{
		$pid = $this->_context->ocid;
		$amount = $this->_context->amount;
		$uid = $this->_context->uid;
		$hash = $this->_context->sig;
		$mid = $this->_context->subid1;
		$oid = $this->_context->oid;
		$title = $this->_context->title;
		$time = $this->_context->time;
		if (empty($mid))
		{
			echo 'ERROR:FATAL';
			exit;
		}
		$mmodel = new Monetization();
		$secretKey = $mmodel->getSecretKeyById($mid);
		if ($secretKey == false)
		{
			echo 'ERROR:FATAL';
			exit;
		}
		$name = 'Epic Social: '. $title . ' - '.  $pid;
		if (md5($uid. $amount . $time. $oid. $secretKey) == $hash)
		{
			$offermodel = new Reward();
			if ($offermodel->exists($uid, $pid))
			{
				echo 'OK';
				exit;
			}
			$usermodel = new User();
			$flag = $usermodel->offerUserCredits($amount, $uid);
			if($flag)
			{
				$offermodel->addRewardByMonetization($uid, $name, $amount, $pid, $oid);
				
				//TODO: epic social offer call back
				
				if ($this->_site['game'] == WHEEL)
				{
					$siteFactor = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$siteFactor = 0.15;
				}
				else if ($this->_site['game'] == POKER)
				{
					$siteFactor = 1;
				}
				
				$revenue = $siteFactor * $mmodel->getMonetizationFactor('epic_social_token_value') * $amount;
				
				$record = new Record($uid);
				$record->addOfferCallbackRecording($amount, $revenue, 'Epic Social');

				$site = new Site();
				if ($this->_site['game'] == SLOT)
				{
					$site->updateJackpot($this->_site['id'], round($amount/5));
				}
				else
				{
					$site->updateJackpot($this->_site['id'], $amount);
				}
				
				$user = $usermodel->getUserById($uid);
				if($user['cam'] == '17' || $user['cam'] == '18'){
					if($user['fired'] != '1'){
						$s2scamModel = new S2scam();
						$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
						$usermodel->setFired($user['id']);
					}
				}
				echo 'OK';
			}
			else
			{
				echo 'ERROR:RESEND';
			}				
		}
		else
		{
			echo 'ERROR:FATAL';
		}
		exit;
	}

	function actionTrialpay()
	{
		$pid = $this->_context->oid;
		$amount = $this->_context->reward_amount;
		if (empty($amount))
		{
			$amount = 0;
		}
		$uid = substr($this->_context->sid, 3);
		$mid = $this->_context->m;
		$hash = $_SERVER['HTTP_TRIALPAY_HMAC_MD5'];
		if (empty($mid))
		{
			header(Util::HTTPStatus(400));
			echo 'Parameter m is required';
			exit;
		}
		if ($mid == 'mm')
		{
			$secretKey = '0c74e7e644';
		}
		else
		{
			echo 'Value of parameter m is invalid';
			exit;
		}
		$name = 'TrialPay '. $pid;
		if (hash_hmac('md5', $_SERVER['QUERY_STRING'], $secretKey) == $hash)
		{
			$offermodel = new Reward();
			if ($offermodel->exists($uid, $pid))
			{
				header(Util::HTTPStatus(406));
				echo 'Duplicate Transaction';
				exit;
			}
			$usermodel = new User();
			$flag = $usermodel->offerUserCredits($amount, $uid);
			if($flag)
			{
				$offermodel->addRewardByMonetization($uid, $name, $amount, $pid);
				
				//TODO: trial pay offer callback
				
				$site = new Site();
				if ($this->_site['game'] == SLOT)
				{
					$site->updateJackpot($this->_site['id'], round($amount/5));
				}
				else
				{
					$site->updateJackpot($this->_site['id'], $amount);
				}
				
				$user = $usermodel->getUserById($uid);
				if($user['cam'] == '17' || $user['cam'] == '18'){
					if($user['fired'] != '1'){
						$s2scamModel = new S2scam();
						$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
						$usermodel->setFired($user['id']);
					}
				}
				
				if ($this->_site['game'] == WHEEL)
				{
					$siteFactor = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$siteFactor = 0.15;
				}
				else if ($this->_site['game'] == POKER)
				{
					$siteFactor = 1;
				}
				$mmodel = new Monetization();
				$revenue = $siteFactor * $mmodel->getMonetizationFactor('trial_pay_token_value') * $amount;
				$record = new Record($uid);
				$record->addOfferCallbackRecording($amount, $revenue, 'Trial pay');
				echo '1';
			}
			else
			{
				header(Util::HTTPStatus(500));
				echo 'Try again later';
			}
		}
		else
		{
			header(Util::HTTPStatus(400));
			echo 'Hash code does not match';
		}
		exit;
	}

	function actionTapjoy(){
		
		//authorize the request
		$allowedIps = array(
			"74.205.58.114",
			"99.132.162.242",
			"99.132.162.245",
			"99.132.162.243",
			"99.132.162.244",
			"173.203.141.129",
			"209.61.169.131",
		);
		$clientIp = $this->_context->server('REMOTE_ADDR');
		$index = array_search($clientIp, $allowedIps);
		
		//an illegal request
		if(false !== $index){
			$secretKey;
			$id = $this->_context->id;
			$snuid = $this->_context->snuid;
			$currency = $this->_context->currency;
			$toEnctype = sprintf("%s:%s:%s:%s", $id, $snuid, $currency, $secretKey);
			$verifier = $this->_context->verifier;
			if(md5($toEnctype) == $verifier){
				$transactionId = $this->_context->id;
				$usermodel = new User();
				$flag = $usermodel->offerUserCreditsByMonetizations($currency, $uid);
				if($flag){
					$offermodel = new Offer();
					$offermodel->addOfferByMonetization($uid, $name, $currencyAmt);
					
					$user = $usermodel->getUserById($uid);
					if($user['cam'] == '17' || $user['cam'] == '18'){
						if($user['fired'] != '1'){
							$s2scamModel = new S2scam();
							$s2scamModel->add($user['cam'], str_replace('CD', '', $user['pub']), $user['pla']);
							$usermodel->setFired($user['id']);
						}
					}
					
					//TODO: tap joy offer callback
					header("HTTP/1.0 200 Success!");
				}else{
					header("HTTP/1.0 403 Failure - do not retry");
				}
			}
		}else{
			
		}
	}
}
?>